package cc.admin.modules.sys.service.impl;

import cc.admin.modules.sys.entity.MessageNotification;
import cc.admin.modules.sys.entity.SysUser;
import cc.admin.modules.sys.mapper.MessageNotificationMapper;
import cc.admin.modules.sys.service.IWeMessageService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Description: wei
 * @Author: shy
 * @Date: 2023-02-23
 * @Version: V1.0.0
 */
@Service
@Slf4j
public class WeMessageServiceImpl extends ServiceImpl<MessageNotificationMapper, MessageNotification> implements IWeMessageService {

	@Autowired
	private KafkaTemplate<String, Object> kafkaTemplate;
	@Autowired
	private MessageNotificationMapper messageNotificationMapper;

	@Autowired
	JdbcTemplate jdbcTemplate;

	@Override
	public void sendWeMessage(SysUser user, JSONObject data, String templateId) {
		String sql = String.format("SELECT distinct username FROM sys_user where status='1' and del_flag='0' and tenant_id = ? and (is_proxy='1' or username = ?)");
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, user.getTenantId(), user.getPhone());
		for (Map map : list) {
			String phone = map.get("username").toString();
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("id", "wechat");
			MessageNotification messageNotification = messageNotificationMapper.selectOne(queryWrapper);
			if (messageNotification != null && "1".equals(messageNotification.getShortMessage())) {
				doSend(phone, data, templateId);
			}
		}
	}

	public void doSend(String phone, JSONObject data, String templateId) {
		JSONObject msg = new JSONObject();
		msg.put("phone", phone);
		msg.put("templateId", templateId);
		msg.put("data", data);
		log.info("给用户:{},推送消息:{}",phone,data.toJSONString());
		kafkaTemplate.send("topic.wei.xin", msg.toJSONString());
	}
}
